package com.liuxing.doctor.controller;

import com.liuxing.doctor.common.Object.ReturnObject;
import com.liuxing.doctor.common.util.DateUtils;
import com.liuxing.doctor.entity.Department;
import com.liuxing.doctor.entity.Doctor;
import com.liuxing.doctor.entity.Patient;
import com.liuxing.doctor.entity.Prescription;
import com.liuxing.doctor.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 行柳
 * 学习使用
 */

/**
 * 处方管理的controller层
 */
@Controller
@Slf4j
@RequestMapping("/prescription")
public class PrescriptionController {
    @Resource
    private PatientService patientService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PrescriptionService prescriptionService;
    @Resource
    private MedicalRecordService medicalRecordService;
    @Resource
    private DoctorService doctorService;
    @RequestMapping("/index")
    public String index(Model model,HttpServletRequest request){
        log.info("_____执行在这儿______");
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        model.addAttribute("doctor",doctor);
        return "main/prescription";
    }
    /**
     * 显示病人列表
     * @return
     */
    @RequestMapping(value = "/patient_list")
    @ResponseBody
    public Object patient_list(HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        //获取医生id的标识字号(除了首字号的所有)，代表该医生专属的
        int len=doctor.getDoctorId().length();
        List<Patient> patients=patientService.queryAllPatients(String.valueOf(Integer.parseInt(doctor.getDoctorId().substring(1,len))));
        Map<String,Object> resMap=new HashMap<>();
        resMap.put("patients",patients);
        return resMap;
    }

    /**
     * 回显病人处方信息
     * @param patient_id
     * @param request
     * @return
     */
    @RequestMapping("/patietn_prescription")
    @ResponseBody
    public Object patietn_prescription(String patient_id,HttpServletRequest request){
        Map<String,Object> resMap=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        resMap.put("patient",patient);
        if(patient.getMedicalRecordId()==0){
            resMap.put("code","0");
            resMap.put("msg","该病人还为诊断病历，请先诊断");
            return resMap;
        }
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        Department department=departmentService.queryDepartmentByDoctorId(doctor.getDoctorId());
        //获得最新的处方记录
        Prescription prescription=prescriptionService.queryPrescriptionsByPatientId(patient_id).stream().sorted((x,y)->
                        DateUtils.formateDateTime(y.getCreateTime()).compareTo(DateUtils.formateDateTime(x.getCreateTime()))
                ).collect(Collectors.toList()).get(0);
        if(patient==null||department==null||prescription==null){
            resMap.put("code","0");
            resMap.put("msg","网络连接错误，请稍后再试。");
            return resMap;
        }
        resMap.put("department",department);
        resMap.put("prescription",prescription);
        return resMap;
    }
    @RequestMapping("/delete")
    @ResponseBody
    @Transactional
    public Object delete(String patient_id,HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        String createDateTime=DateUtils.formateDateTime(new Date());

        ReturnObject returnObject=new ReturnObject();
        int resCode1=prescriptionService.deletePrescriptionsByPatientId(patient_id);
        //给病人新建一个新的空的处方
        Map<String,Object> createNullPrescription=new HashMap<>();
        createNullPrescription.put("createDateTime",createDateTime);
        createNullPrescription.put("patient_id",patient_id);
        createNullPrescription.put("doctor_id",doctor.getDoctorId());
        prescriptionService.createNullPrescriptionByPatientId(createNullPrescription);
        if(resCode1>0){
            returnObject.setCode("1");
            returnObject.setMessage("删除成功");
        }else{
            returnObject.setMessage("网络连接错误，强稍后再试");
        }
        return returnObject;
    }

    /**
     * 保存或更新处方
     * @param patient_id
     * @param prescriptionContent
     * @return
     */
    @RequestMapping("/savePrescription")
    @ResponseBody
    @Transactional
    public Object savePrescription(String patient_id, @RequestParam("medicine") String prescriptionContent){
        ReturnObject returnObject=new ReturnObject();
        Patient patient=patientService.queryById(patient_id);
        if(patient.getMedicalRecordId()==0){
            returnObject.setMessage("该病人还为诊断病历，请先诊断");
            return  returnObject;
        }
        String editTime=DateUtils.formateDateTime(new Date());
        Map<String,Object> map=new HashMap<>();
        //获得最新的处方记录
        Prescription prescription=prescriptionService.queryPrescriptionsByPatientId(patient_id).stream().sorted((x,y)->
                    DateUtils.formateDateTime(y.getCreateTime()).compareTo(DateUtils.formateDateTime(x.getCreateTime()))
                ).collect(Collectors.toList()).get(0);
        map.put("prescriptionContent",prescriptionContent);
        map.put("editTime",editTime);
        map.put("prescriptionId",prescription.getPrescriptionId());
        int resCode=prescriptionService.updatePatientPrescription(map);
        if(resCode==1){
            returnObject.setCode("1");
            returnObject.setMessage("保存成功");
            return returnObject;
        }
        returnObject.setMessage("网络连接错误，请稍后再试");
        return returnObject;
    }

    /**
     * 新建处方信息
     * @param patient_id
     * @param prescription
     * @param request
     * @return
     */
    @RequestMapping("/createPrescription")
    @ResponseBody
    public Object createPrescription(String patient_id,String prescription,HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        Map<String,Object> resMap=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        if(patient.getMedicalRecordId()==0){
            resMap.put("code","0");
            resMap.put("msg","该病人还为诊断病历，请先诊断");
            return resMap;
        }
        String dateTime=DateUtils.formateDateTime(new Date());
        Map<String,Object> map=new HashMap<>();
        map.put("dateTime",dateTime);
        map.put("patient_id",patient_id);
        map.put("prescription_content",prescription);
        map.put("doctor_id",doctor.getDoctorId());
        int resCode=prescriptionService.createPrescriptionByPatient(map);
        if(resCode==1){
            resMap.put("dateTime",DateUtils.formateDate(new Date()));
            resMap.put("prescription",prescription);
            resMap.put("code","1");
            return resMap;
        }
        resMap.put("msg","网络连接错误，请稍后再试");
        return resMap;
    }

    @RequestMapping("/print")
    @ResponseBody
    public Object print(String patient_id,HttpServletRequest request){
        Doctor doctor= (Doctor) request.getSession().getAttribute("doctor");
        Map<String,Object> resMap=new HashMap<>();
        Patient patient=patientService.queryById(patient_id);
        resMap.put("patientName",patient.getPatientName());
        resMap.put("patientSexy",patient.getPatientSex());
        resMap.put("patientAge",patient.getPatientAge());
        if(patient.getMedicalRecordId()==0){
            resMap.put("code","0");
            resMap.put("msg","请先为该病人创建新的病历");
            return resMap;
        }
        //获得最新的处方记录
        Prescription prescription=prescriptionService.queryPrescriptionsByPatientId(patient_id).stream().sorted((x,y)->
                DateUtils.formateDateTime(y.getCreateTime()).compareTo(DateUtils.formateDateTime(x.getCreateTime()))
        ).collect(Collectors.toList()).get(0);
        resMap.put("prescription",prescription.getPrescriptionContent());
        resMap.put("date",DateUtils.formateDate(prescription.getCreateTime()));
        resMap.put("doctorName",doctor.getDoctorName());
        resMap.put("department",doctor.getDoctorDepartment());
        return resMap;
    }
}
